package com.example.lib_base.mvvm

import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat
import kotlin.coroutines.cancellation.CancellationException

open class BaseViewModel:ViewModel() {
  fun <T> httpRequest(
    requestCall: suspend () -> Res<T>?,
    onSuccess: (T) -> Unit,
    onError: ((String) -> Unit)? = null
) {
    viewModelScope.launch {
        try {
            val res = requestCall()
            if (res == null) {
                val errorMsg = "请求返回空数据"
                Log.e("TAG", errorMsg)
                onError?.invoke(errorMsg)
                return@launch
            }

            Log.d("TAG", "httpRequest: res raw data = $res")

            if (res.code == 200) {
                onSuccess(res.data)
            } else {
                val errorMsg = "请求失败"
                ToastUtils.showShort(errorMsg)
                Log.e("TAG", errorMsg)
                onError?.invoke(errorMsg)
            }
        } catch (e: CancellationException) {
            val errorMsg = "请求取消"
            Log.e("TAG", errorMsg)
            ToastUtils.showShort(errorMsg)
            onError?.invoke(errorMsg)
        } catch (e: Exception) {
            val errorMsg = when {
                e is java.io.EOFException -> "网络连接异常，请检查网络后重试"
                e is IllegalStateException && e.message?.contains("closed") == true -> "连接已关闭，请重试"
                e.message?.contains("404") == true -> "接口地址不存在(404)"
                e.message?.contains("timeout") == true -> "网络超时，请重试"
                e.message?.contains("ConnectException") == true -> "无法连接到服务器"
                else -> "请求异常: ${e.message}"
            }
            ToastUtils.showShort(errorMsg)
            Log.e("TAG", errorMsg, e)
            onError?.invoke(errorMsg)
        }
    }
}
    fun  gettime(time:Long): String? {
        return SimpleDateFormat("HH:mm:ss").format(time)
    }




}